﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yunlib.Common;
using Yunlib.Entity;
using YunLib.BLL;
using YunLib.Common;

namespace YunLib.SIP2
{
    #region summary
    ///     用户登录------93
    ///     系统状态------99
    ///     请求重发------97
    ///     用户状态------23
    ///     用户信息------63
    ///     阻塞用户------01
    ///     激活用户------25
    ///     图书信息------17
    ///     借书操作------11
    ///     续借操作------29
    ///     续借所有------65
    ///     还书操作------09
    ///     缴费操作------37
    ///     用户退出------35
    ///     server
    ///     用户登录返回------94
    ///     系统状态返回------98
    ///     请求重发返回------96
    ///     用户状态返回------24
    ///     用户信息返回------64
    ///     激活用户返回------26
    ///     图书信息返回------18
    ///     借书操作返回------12
    ///     续借操作返回------30
    ///     续借所有返回------66
    ///     还书操作返回------10
    ///     缴费操作返回------38
    ///     用户退出返回------36
    #endregion summary
    public partial class Form1 : Form
    {
        private Socket socketserver;

        private byte[] bytes;
        
        private string pickhour = null; //时间控件的小时部分
        private string pickmiun = null; //时间控件的分钟部分
        private int flag = 0; // 程序是否执行完的标志0为完了，1为还在执行。
        private string FileName; //INI文件名
        private DateTime time1;
        private DateTime time2;
        private Thread mythread;


        //GDLISXP INFO
        private string errorinfo = "";
        private string sxrq = ""; //失效日期
        private string gszx = ""; //挂失注销
        private string MM = ""; //密码
        private int ywj; //已外借
        private int kwj; //可外借
        private double qfk; //欠罚款
        private string wjqxlx = ""; //外借期限类型
        private int wjqx; //外借期限
        private string yghrq = ""; //应归还日期
        private int zjm; //主键码
        private int xnks; //虚拟库室
        private string tm = ""; //题名
        private string gcdz = ""; //馆藏地址
        private string ssh = ""; //索书号
        private string yxxjcs = "";//允许续借次数
        private string jbdm = "";//级别代码
        private string dwdm = "";//单位代码
        private string xjcs = "";//读者续借次数
        private string wjsj = "";//流通库外借时间
        
        private decimal pirce;

        private ReaderInfoBLL rib = new ReaderInfoBLL();
        private ReturnOrBrBLL BLL = new ReturnOrBrBLL();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string connStr = ConfigurationManager.ConnectionStrings["WayLibDB"].ConnectionString.ToString();
            string ip = ConfigurationManager.AppSettings["IP"].ToString();
            int port = int.Parse(ConfigurationManager.AppSettings["Port"].ToString());
            textBox1.Text = connStr;
            textBox2.Text = ip;
            textBox3.Text = port.ToString();


            CheckForIllegalCrossThreadCalls = false;
            
            bytes = new byte[1024];
            try
            {
                //改变
                socketserver = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var ipep = new IPEndPoint(IPAddress.Parse(ip), port);
                socketserver.Bind(ipep);
                socketserver.Listen(10);
                SetLog("服务已经启动，端口：" + port + "已经绑定，监听中..." + Environment.NewLine);
                socketserver.Blocking = true;
            }
            catch (Exception ex)
            {
                //  MessageBox.Show("创建套接字失败：" + ex.Message);
                SetLog("创建套接字失败，程序不能进行:" + ex.Message + "" +Environment.NewLine);
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                return;
            }
            SetLog("初始化套接字完成！" + Environment.NewLine);
            try
            {
                mythread = new Thread(BeginSocket);
                mythread.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "完成", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                return;
            }

            //连接数据库
            try
            {
                SqlConnection conn = new SqlConnection(connStr);
                conn.Open();
                conn.Close();
            }
            catch (Exception ex)
            {
                richTextBox1.Text = richTextBox1.Text + "连接数据库失败：" + ex.Message + "";
                return;
            }
            richTextBox1.Text = richTextBox1.Text + "数据库连接成功！";

        }

        private void BeginSocket()
        {
            while (true)
            {
                Socket clientSocket = socketserver.Accept();

                // clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                SetLog("有客户端连接进来了！" + Environment.NewLine);
                receiveThread.Start(clientSocket);
                Thread.Sleep(50);
                Application.DoEvents();
            }
        }

        /// <summary>
        /// 接收处理消息
        /// </summary>
        /// <param name="clientSocket"></param>
        private void ReceiveMessage(object clientSocket)
        {
            //   Control.CheckForIllegalCrossThreadCalls = false;
            bool isconn = true;
            string SendMessage = "";

            // if (socketclient!=null&&socketclient.Connected)
            //{
            Socket mysocketclient = (Socket)clientSocket;
            while (isconn)
            {
                try
                {
                    mysocketclient.Receive(bytes);
                    string ReceiveMessage = Encoding.UTF8.GetString(bytes);
                    if (ReceiveMessage.Substring(0, 1) == "\0")
                    {
                        SetLog("客户端断开" + Environment.NewLine);

                        mysocketclient.Close();
                    }
                    else
                    {
                        SetLog(DateTime.Now + "===" + "获得信息：=>" + ReceiveMessage.Trim() + "" + Environment.NewLine);
                        // SetLog(""+Environment.NewLine); 
                        string Opertion = ReceiveMessage.Substring(0, 2);
                        switch (Opertion)
                        {
                            case "09": //还书
                                SetLog(DateTime.Now + "===" + "还书操作" + "" + Environment.NewLine);
                                SendMessage = ReceivBackBook(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;

                            case "11": //借书
                                SetLog(DateTime.Now + "===" + "借书操作" + "" + Environment.NewLine);
                                SendMessage = ReceivBorrow(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;
                            //case "19": //更新图书操作
                            //    SetLog(DateTime.Now + "===" + "更新图书操作" + "" + Environment.NewLine);
                            //    SendMessage = ReceivUpdateBookInfo(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            case "17": //查询图书信息
                                SetLog(DateTime.Now + "===" + "查询图书信息" + "" + Environment.NewLine);
                                SendMessage = ReceivBookInfo(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;

                            case "29": //续借
                                SetLog(DateTime.Now + "===" + "续借操作" + "" + Environment.NewLine);
                                SendMessage = ReceivRenew(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;
                            //case "35": //用户退出
                            //    SetLog(DateTime.Now + "===" + "用户退出" + "" + Environment.NewLine);
                            //    SendMessage = ReceivLogout(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            //case "53": //读者预付款金额
                            //    SetLog(DateTime.Now + "===" + "读者预付款金额" + "" + Environment.NewLine);
                            //    SendMessage = ReceivAdvanceCharge(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            //case "59": //缴费
                            //    SetLog(DateTime.Now + "===" + "缴费流程" + "" + Environment.NewLine);
                            //    SendMessage = ReceivPayment(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            case "63": //读者查询
                                SetLog(DateTime.Now + "===" + "读者查询" + "" + Environment.NewLine);
                                SendMessage = ReceivQueryReader(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;
                            //case "77": //读者照片更新
                            //    SetLog(DateTime.Now + "===" + "读者照片更新" + "" + Environment.NewLine);
                            //    SendMessage = ReceivUpdateReaderPhoto(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            //case "81": //办证
                            //    SetLog(DateTime.Now + "===" + "读者证处理" + "" + Environment.NewLine);
                            //    SendMessage = ReceivCreatReader(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            //case "91": //读者查重
                            //    SetLog(DateTime.Now + "===" + "读者查重" + "" + Environment.NewLine);
                            //    SendMessage = ReceivReaderRepeat(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            //case "93": //登录
                            //    SetLog(DateTime.Now + "===" + "登录操作" + "" + Environment.NewLine);
                            //    SendMessage = ReceivLogin(ReceiveMessage);
                            //    if (SendMessage != "")
                            //    {
                            //        mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                            //        SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                            //    }
                            //    break;
                            case "99": //链接
                                SetLog(DateTime.Now + "===" + "链接操作" + "" + Environment.NewLine);
                                SendMessage = ReceivConnection(ReceiveMessage);
                                if (SendMessage != "")
                                {
                                    mysocketclient.Send(Encoding.UTF8.GetBytes(SendMessage));
                                    SetLog(DateTime.Now + "===" + "发送:" + SendMessage.Trim() + "" + Environment.NewLine);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    SetLog("出现错误:" + ex.Message + "");
                    mysocketclient.Close();
                    isconn = false;
                }
                
                Thread.Sleep(50);
                Application.DoEvents();
            }
        }

        #region Socket响应事件
        
        

        #region 09 还书处理

        //09N20150111    155504                  AP|AO|AB0000001|AC|BIN|AYXHXTSG|
        public string ReceivBackBook(string st)
        {
            List<string> li = Exstring(st);
            string ok = "";
            string barcode = "";
            try
            {
                foreach (var item in li)
                {
                    if (item.Length > 2)
                    {
                        string headStr = item.Substring(0, 2);
                        if (headStr == "AB")
                        {
                            barcode = item.Substring(2).Trim();
                        }
                    }
                }
                ok = SendBackBook(barcode);

                return ok;
            }catch(Exception ex)
            {
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                return ok;
            }
        }

        /*********************************************************
         * 101YNN20131111    165920AO
         * |AB0009030
         * |AQ999_ZWSK-中文书库
         * |AJ彩图世界名著100集．黄星篇
         * |AA440506
         * |ST02
         * |CK001
         * |CTHL_CN02]]湖里中文期刊
         * |CF
         * |KCI18/2148-3
         * |CH湖里区中文期刊ATNPR12.0/12.0
         * |CLsort bin A1
         * |AF该图书是外馆图书。请遵照规则处理2013-12-11
         * |AG图书 彩图世界名著100集．黄星篇[0009030]已于:20131111归还2013-12-11
         * |AY2AZA3FF
         * 
         ************************************************************/

        public string SendBackBook(string barCode)
        {
            
            string readerid = "";
            // string zjm = "";

            // string bookname;
            string ok = "";
            string head = "100YNN" + DateTime.Now.ToString("yyyyMMdd     HHmmss" + "AO");
            string AB = "|AB"+barCode;
            string AQ = "|AQ";
            string AJ = "|AJ";
            string AA = "|AA";
            string ST = "|ST02";
            string CK = "|CK001";
            string CT = "|CT001";
            string CF = "|CF";
            string KC = "|KC";
            string CH = "|CH";
            string CL = "|CLsort bin A1";
            string AF = "|AF";
            string AG = "|AG";
            string AY = "|AYXHXTSG";
            try
            {
                if (string.IsNullOrWhiteSpace(barCode))
                {
                    AF += "图书归还失败失败原因===>还书条码不能为空";
                    AG += "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>还书条码不能为空";
                    return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
                }
                else
                {
                    // ChangeKuInfo model = BLL.GetBorrowBooksInfoByBarcode(barCode);
                    DataTable dt = BLL.GetSIP2LendInfoByBarCode(barCode);

                    if (dt.Rows.Count == 0)
                    {
                        AF = "|AF图书归还失败失败原因===>该书没有借阅";
                        AG = "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>该书没有借阅";
                        return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
                    }
                    DateTime time1 = (dt.Rows[0]["应归还时间"].ToString() == "") ? DateTime.Parse("1990-1-1") : Convert.ToDateTime(dt.Rows[0]["应归还时间"].ToString());
                    //if (time1 < DateTime.Now)
                    //{
                    //    AF = "|AF图书归还失败失败原因===>该书已超期，请到柜台归还";
                    //    AG = "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>该书已超期，请到柜台归还";
                    //    return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
                    //}


                    AQ = "|AQ" + dt.Rows[0]["部门名称"].ToString();
                    AJ = "|AJ" + dt.Rows[0]["题名"].ToString();
                    AA = "|AA" + dt.Rows[0]["读者条码"].ToString();
                    KC = "|KC" + dt.Rows[0]["索书号"].ToString();
                    CH = "|CH" + dt.Rows[0]["题名"].ToString() + "ATN" + "PR" + dt.Rows[0]["单价"].ToString();
                    ChangeLogInfo logModel = new ChangeLogInfo
                    {
                        OperateType = "H",
                        BarCode = barCode,
                        LoginAccount = barCode,
                        ReaderCode = dt.Rows[0]["读者条码"].ToString(),
                        DealTime = DateTime.Now,
                        Penalty = 0.00m,
                        Operator = 1,
                        ID = int.Parse(dt.Rows[0]["主键码"].ToString())
                    };

                    bool flag = true;

                    //还书成功，读者已借书籍书减少1本
                    flag = rib.UpdateUserBoorowNum((int)dt.Rows[0]["已外借"] - 1, dt.Rows[0]["读者条码"].ToString());

                    if (!flag)
                    {
                        AF = "|AF图书归还失败失败原因===>修改用户信息失败";
                        AG = "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>修改用户信息失败";
                        return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
                    }


                    bool res = BLL.DeleteChangeInfoByBarCode(logModel.BarCode);

                    if (res)
                    {
                        head = "101YNN" + DateTime.Now.ToString("yyyyMMdd     HHmmss" + "AO");
                        AF = "|AF图书归还成功";
                        AG = "|AG图书 " + tm + "[" + barCode + "]已于:" + time1 + "归还！";

                    }
                    else
                    {
                        AF = "|AF图书归还失败失败原因===>删除流通记录失败";
                        AG = "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>删除流通记录失败";
                        rib.UpdateUserBoorowNum((int)dt.Rows[0]["已外借"], dt.Rows[0]["读者条码"].ToString());
                    }
                    return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
                }
            }catch(Exception ex)
            {
                AF = "|AF图书归还失败失败原因===>"+ex.Message;
                AG = "|AG图书 [" + barCode + "] 归还失败！ 失败原因===>"+ex.Message;
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                return head + AB + AQ + AJ + AA + ST + CK + CT + CF + KC + CH + CL + AF + AG + AY;
            }
           
        }

        #endregion

        #region 11 借书处理

        /// <summary>
        ///     发出指令
        ///     11YN19960212    10051419960212    100514AO|AA440506|AB0009030|AC|AY3AZEDB7|
        ///     11YN20150109    17431120150109    174311AO|AA1|AB0000001|AC11|AYXHXTSG|
        ///     121NNY20141202    161111AO|AA0100000369090|AB0100103173661|AJ葡萄酒配餐宝典|AH2015-01-02|CHATNPR89.0/89.0|AF图书【103173661】借书处理成功！ 应还日期(2015-01-02)|AG读者[0100000369090]借书 葡萄酒配餐宝典[0100103173661]成功应还日期:2015-01-02|AY3AZD2A1

        ///     解析（）
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        public string ReceivBorrow(string st)
        {
            List<string> li = Exstring(st);

            string ok = "";
            /*
             * 处理时间 
             */
            string ReaderID = "";
            string BarCode = "";
            string PWD = null;
            foreach (var item in li)
            {
                if (item.Length >= 2)
                {
                    string headStr = item.Substring(0, 2);
                    if (headStr == "AA")
                    {
                        ReaderID = item.Substring(2).Trim();
                    }
                    else if (headStr == "AB")
                    {
                        BarCode = item.Substring(2).Trim();
                    }
                    else if (headStr == "AD")
                    {
                        PWD = item.Substring(2).Trim();
                    }

                }
            }


            ok = SendBorrow(BarCode, ReaderID, PWD);
            return ok;
        }

        /// <summary>
        ///     返回指令
        ///     121NNY20131111    163307AO|AA440506|AB0009030|
        ///     AJ彩图世界名著100集．黄星篇|AH2013-12-11|CHATYPR12.0/12.0|
        ///     AF图书【0009030】借书处理成功！ 应还日期(2013-12-11)|
        ///     AG读者[440506]借书 彩图世界名著100集．黄星篇[0009030]
        ///     成功应还日期:2013-12-11|AY3AZD2A1
        /// 
        /// 121NNY20141202    161111AO|AA0100000369090|AB0100103173661
        /// |AJ葡萄酒配餐宝典|AH2015-01-02|CHATNPR89.0/89.0
        /// |AF图书【103173661】借书处理成功！ 应还日期(2015-01-02
        /// )|AG读者[0100000369090]借书 葡萄酒配餐宝典[0100103173661]成功应还日期:2015-01-02|AY3AZD2A1

        ///     1.12
        ///     2.1
        ///     3.NNY
        ///     4.时间
        ///     5.AO
        ///     6.AA读者条码
        ///     7.AB图书条码
        ///     8.AJ图书题名
        ///     9.AH图书应还日期
        ///     10.CH图书的简单信息：AT（是否有附件：Y表示有，N表示无）PR（图书价格）
        ///     11.AF提示信息
        ///     12.AG打印信息
        ///     13.AY验证码 ///sip协议里面没有
        /// </summary>
        /// <param name="barcode"></param>
        /// <param name="readerid"></param>
        /// <returns></returns>
        public string SendBorrow(string barcode, string readerid, string password = null)
        {
            string ok = "";


            string head = "120NNY" + DateTime.Now.ToString("yyyyMMdd     HHmmss");
            string AO = "AO";
           string AA = "|AA" + readerid;
           string  AB = "|AB" + barcode;
           string AJ = "|AJ";
           string AH = "|AH" ;
           string CH = "|CHATNPR";
            string AF = "|AF";
            string AG = "|AG";
            string AY = "|AYXHXTSG";
            try
            {
                DataTable dt = BLL.GetSIP2BookInfoByBarCode(barcode);

                if (dt.Rows.Count > 0)
                {
                    AJ = "|AJ" + dt.Rows[0]["题名"];
                    CH = "|CHATNPR" + dt.Rows[0]["单价"];
                }
                else
                {
                    AF = "|AF图书借阅失败，失败原因===>图书条码错误";
                    AG = "|AG图书借阅失败！ 失败原因===>图书条码错误";
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }

                bool canBorrow = dt.Rows[0]["允许外借"].ToBool();
                if (!canBorrow)
                {
                    AF = "|AF图书借阅失败失败原因===>该书不可外借";
                    AG = "|AG图书借阅失败！ 失败原因===>该书不可外借";
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }

                DataTable dtUser = rib.GetUser(readerid);
                if (dtUser.Rows.Count <= 0)
                {
                    AF = "|AF图书借阅失败失败原因===>读者条码错误";
                    AG = "|AG图书借阅失败！ 失败原因===>读者条码错误";
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }

                if (Convert.ToDateTime(dtUser.Rows[0]["失效日期"].ToString()) < DateTime.Now)
                {
                    //读者卡失效了

                    AF = "|AF图书借阅失败失败原因===>读者卡已失效";
                    AG = "|AG图书借阅失败！ 失败原因===>读者卡已在：{0}失效".FormatWith(dtUser.Rows[0]["失效日期"].ToString());
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }
                string str = dtUser.Rows[0]["挂失日期"].ToString();
                if (!string.IsNullOrWhiteSpace(dtUser.Rows[0]["挂失日期"].ToString()))
                {
                    AF = "|AF图书借阅失败失败原因===>读者卡已失效";
                    AG = "|AG图书借阅失败！ 失败原因===>读者卡已在：{0}挂失".FormatWith(dtUser.Rows[0]["挂失日期"].ToString());
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }

                if (dtUser.Rows[0]["密码"].ToString().Trim() != password)
                {
                    AF = "|AF图书借阅失败失败原因===>密码错误";
                    AG = "|AG图书借阅失败！ 失败原因===>密码错误";
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }



                bool HasExpire = false;
                DataTable dt1 = BLL.GetCirculationByUserId(readerid);
                var list = DataTable2List<ChangeKuInfo>.ConvertToModel(dt1);
                foreach (var item in list)
                {
                    var reTime = item.ShouldReturnTime;
                    if (reTime < DateTime.Now)
                    {
                        HasExpire = true;
                    }
                }
                if (HasExpire)
                {
                    AF = "|AF图书借阅失败失败原因===>有超期书籍未归还";
                    AG = "|AG图书借阅失败！ 失败原因===>有超期书籍未归还";
                    return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                }
                else
                {
                    if ((int)dtUser.Rows[0]["可外借"] - (int)dtUser.Rows[0]["已外借"] <= 0)
                    {
                        AF = "|AF图书借阅失败失败原因===>可外借数量已达上限";
                        AG = "|AG图书借阅失败！ 失败原因===>可外借数量已达上限";
                        return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                    }
                    else
                    {
                        var bb = BLL.GetBorrowBooksInfoByBarcode(barcode);
                        if (bb != null)
                        {
                            AF = "|AF图书借阅失败失败原因===>该书已借阅";
                            AG = "|AG图书借阅失败！ 失败原因===>该书已借阅";
                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }

                        bool flag = rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, readerid);

                        if (!flag)
                        {
                            AF = "|AF图书借阅失败失败原因===>修改用户借阅信息失败";
                            AG = "|AG图书借阅失败！ 失败原因===>修改用户借阅信息失败";
                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }

                        DataTable dtc = BLL.GetcirculationParmar(dt.Rows[0]["虚拟库室"].ToString(), dtUser.Rows[0]["级别代码"].ToString(), dtUser.Rows[0]["单位代码"].ToString());

                        if (dtc.Rows.Count == 0)
                        {
                            AF = "|AF图书借阅失败失败原因===>获取流通参数定义失败";
                            AG = "|AG图书借阅失败！ 失败原因===>获取流通参数定义规则失败";
                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }

                        DateTime returnTime = DateTime.Now;
                        if (dtc.Rows[0]["外借期限类型"].ToString() == "M")
                        {

                            returnTime = DateTime.Now.AddMonths(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                        }
                        else if (dtc.Rows[0]["外借期限类型"].ToString() == "D")
                        {
                            returnTime = DateTime.Now.AddDays(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                        }
                        else
                        {
                            returnTime = DateTime.Now.AddYears(int.Parse(dtc.Rows[0]["外借期限"].ToString()));
                        }

                        ChangeKuInfo kuInfo = new ChangeKuInfo
                        {

                            ID = int.Parse(dt.Rows[0]["主键码"].ToString()),
                            BarCode = barcode,
                            LoginAccount = barcode,
                            BorrowTime = DateTime.Now,
                            ReaderCode = readerid,
                            OnceBorrowCount = BLL.GetOnceBorrowCount(dtUser.Rows[0][2].ToString()),
                            ShouldReturnTime = returnTime
                        };


                        //插入流通库
                        bool flag2 = BLL.AddCirculation(kuInfo);
                        if (!flag2)
                        {
                            AF = "|AF图书借阅失败失败原因===>插入流通记录失败";
                            AG = "|AG图书借阅失败！ 失败原因===>插入流通记录失败";
                            rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, readerid);
                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }


                        ChangeLogInfo logInfo = new ChangeLogInfo
                        {
                            OperateType = "J",
                            BarCode = barcode,
                            LoginAccount = barcode,
                            DealTime = DateTime.Now,
                            ID = int.Parse(dt.Rows[0]["主键码"].ToString()),
                            Penalty = 0,
                            ReaderCode = readerid,
                            Operator = 1
                        };

                        //插入流通日志
                        flag = BLL.InsertLTKOneInfo(logInfo);
                        if (!flag)
                        {
                            AF = "|AF图书借阅失败失败原因===>插入流通日志失败";
                            AG = "|AG图书借阅失败！ 失败原因===>插入流通日志失败";
                            rib.UpdateUserBoorowNum((int)dtUser.Rows[0]["已外借"] + 1, readerid);
                            BLL.DeleteChangeInfoByBarCode(logInfo.BarCode);
                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }
                        else
                        {

                            head = "121NNY" + DateTime.Now.ToString("yyyyMMdd     HHmmss");
                            AH += returnTime;
                            AG = "|AG读者[" + readerid + "]借书 " + tm + "[" + barcode + "]";
                            AF = "|AF图书【" + barcode + "】借书处理成功！ 应还日期(" + yghrq + ")";

                            return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
                        }

                    }

                }
            }catch(Exception ex)
            {
                AF = "|AF图书借阅失败失败原因===>"+ex.Message;
                AG = "|AG图书借阅失败！ 失败原因===>"+ex.Message;
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                return head + AO + AA + AB + AJ + AH + CH + AF + AG + AY;
            }
            
        }

        #endregion

        #region 17 图书信息查询

        /* 17<transaction date><institution id>< item identifier ><terminal password> 
         * 1720080828    105715AO|AB0000001|AY1AZF7E3|
         * 1801000120131104    145106CF00000
         * |AOQD|AA|AB0007293
         * |AJ战后日本的经济起飞
         * |AW李公绰著|AK7-217-00475-6|RE0|CK001|CH3.1/3.1
         *|KCF131.3/4082|CTQD_CN02]]青岛中文期刊
         * |AQQD_ZWQK|AP999_ZWSK|BG|PB湖南人民出版社
         * |SJ经济|PG324页|KP|AF|AG|AY0AZC05B
         * 
         * 
         * 
         */
        private string ReceivBookInfo(string ReceiveMessage)
        {
            
            List<string> li = Exstring(ReceiveMessage);
            string barcode = "";
            foreach(var item in li)
            {
                if (item.Length > 2)
                {
                    string headStr = item.Substring(0, 2);
                    if (headStr == "AB")
                    {
                        barcode = item.Substring(2).Trim();
                        break;
                    }
                }
            }
            
            string Head = "18000001" + DateTime.Now.ToString("yyyyMMdd     HHmmss") + "CF0000";
            string AO = "|AO";
            string AA = "|AA";
            string AB = "|AB" + barcode;
            string AJ = "|AJ";//题名
            string AW = "|AW";//责任者
            string AK = "|AK";//ISBN
            string RE = "|RE";//是否有预约
            string CH = "|CH";//单价
            string KC = "|KC";//索书号
            string CT = "|CT";//流通类型
            string AQ = "|AQ";//馆藏地址
            string AP = "|AP";//当前馆藏地址
            string BG = "|BG";//预约了该书的读者条码号
            string PB = "|PB";//出版者
            string SJ = "|SJ";//主题词
            string PG = "|PG";//页数
            string CK = "|CK001";
            string KP = "|KP";//架位号
            string AF = "|AF";
            string AH = "|AH";//应归还时间
            string AG = "|AG";
            string AY = "|AYXHXTSG";
            try
            {
                var dt = BLL.GetSip2BookDescByBarCode(barcode);

                if (dt.Rows.Count > 0)
                {
                    Head = "18040001" + DateTime.Now.ToString("yyyyMMdd     HHmmss") + "CF0000";
                    AA += dt.Rows[0]["AA"].ToString();
                    AJ += dt.Rows[0]["AJ"].ToString();
                    AW += dt.Rows[0]["AW"].ToString();
                    AK += dt.Rows[0]["AK"].ToString();

                    CH += dt.Rows[0]["CH"].ToString();
                    KC += dt.Rows[0]["KC"].ToString();
                    CT += dt.Rows[0]["CT"].ToString();
                    AQ += dt.Rows[0]["AQ"].ToString();

                    BG += dt.Rows[0]["BG"].ToString();
                    if (string.IsNullOrWhiteSpace(dt.Rows[0]["BG"].ToString()))
                    {
                        RE += 0;
                    }
                    else
                    {
                        RE += 1;
                    }

                    PB += dt.Rows[0]["PB"].ToString();

                    string ah = dt.Rows[0]["AH"].ToString();
                    if (ah != "1900/1/1 0:00:00")
                    {
                        AH += dt.Rows[0]["AH"].ToString();
                    }

                    AF += "获取流通记录成功";
                    AG += "获取流通记录成功";
                }
                else
                {
                    AF += "获取流通记录失败";
                    AG += "获取流通记录失败";
                }
                return Head + AO + AA + "|AB" + AB + AJ + AW + AK + RE + CK + CH + KC + CT + AQ + AP + BG + PB + SJ + PG + KP + AF + AH + AG + AY;
            }
            catch (Exception ex)
            {
                AF += "获取流通记录出错";
                AG += "获取流通记录出错";
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);

                return Head + AO + AA + "|AB" + AB + AJ + AW + AK + RE + CK + CH + KC + CT + AQ + AP + BG + PB + SJ + PG + KP + AF + AH + AG + AY;
            }
            
            
        }
        #endregion

        #region 29 续借处理
        /* 29<third party allowed><no block><transaction date><nb due date><institution id>
         * <patron identifier><patron password>
         * <item identifier><title identifier>
         * <terminal password><item properties><fee acknowledged> 
         * 
         * 29YY20141201    02565420141201    025654AO|AA|AD|AB|AJ|AC|CH|BO
         * 
         *  30<ok><renewal ok><magnetic media><desensitize>
         *  <transaction date><institution id><patron identifier><item identifier>
         *  <title identifier><due date><fee type><security inhibit><currency type>
         *  <fee amount><media type><item properties><transaction id>
         *  <screen message>
         *  <print line> 
         * 300YYY20141201    025654AO|AA|AB|AJ|AH|BT|CI|BH|BV|CK|CH|BK|AF|AG
         * 
         * 1.判断是否能续借
         * 2.如果能续借几次，在流通库里去判断是否足够
         * 3.在流通库更新续借时间和续借次数
         * 
         */
        public string ReceivRenew(string st)
        {
            List<string> li = Exstring(st);
            string ok = "";
            string AA = "";//读者证号
            string AD = "";//密码
            string AB = "";//条形码
            string TM = "";//题名
            string AC = "";//
            string CH = "";//读者欠费记录
            string BO = "";//fee ???

            for (int i = 0; i < li.Count; i++)
            {
                string str = li[i].Substring(0, 2);

                string str1 = li[i].ToString().Substring(2).Trim();

                if (!string.IsNullOrWhiteSpace(str1))
                {

                    if (str == "AA")
                    {
                        AA = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "AD")
                    {
                        AD = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "AB")
                    {
                        AB = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "TM")
                    {
                        TM = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "CH")
                    {
                        CH = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "AC")
                    {
                        AC = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "BO")
                    {
                        BO = li[i].ToString().Substring(2).Trim();
                    }
                }
            }
            
            string BT = "|BT";
            string CI = "|CI";
            string BH = "|BH";
            string BV = "|BV";
            string CK = "|CK";//
            //   string CH = "|CH";//单价
            string BK = "|BK";//
            string AF = "|AF";
            string AG = "|AG";
            string AH = "|AH";
            string head = "300YNN" + DateTime.Now.ToString("yyyyMMdd     HHmmss") + "AO";
            string AJ = "|AJ";
            string AY = "|AYXHXTSG";

            //判断条码是否为空
            if (string.IsNullOrWhiteSpace(AB))
            {
                AF += "图书归还失败失败原因===>还书条码不能为空";
                AG += "|AG图书 [" + AB + "] 归还失败！ 失败原因===>还书条码不能为空";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }
            //获取图书馆藏信息
            DataTable dt = BLL.GetSIP2BookInfoByBarCode(AB);

            if (dt.Rows.Count > 0)
            {
                TM = dt.Rows[0]["题名"].ToString();
             //   CH = "|CHATNPR" + dt.Rows[0]["单价"];
            }
            else
            {
                AF = "|AF图书借阅失败，失败原因===>图书条码错误";
                AG = "|AG图书借阅失败！ 失败原因===>图书条码错误";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }

            ChangeKuInfo ck = BLL.GetBorrowBooksInfoByBarcode(AB);
            if (ck == null)
            {

                AF = AF + "图书【" + TM + "】续借处理失败 原因:=>没有借阅记录";
                AG = AG + "读者[" + AB + "]续借失败原因:=>没有借阅记录";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }

            var dtUser = rib.GetUser(ck.ReaderCode);


            DataTable dtc = BLL.GetcirculationParmar(ck.DummyKu.ToString(), dtUser.Rows[0]["级别代码"].ToString(), dtUser.Rows[0]["单位代码"].ToString());

            string str11 = dtc.Rows[0]["允许续借次数"].ToString();
            if (ck.OnceBorrowCount >= int.Parse(dtc.Rows[0]["允许续借次数"].ToString())) 
            {
                AF = AF + "图书【" + TM + "】续借处理失败 原因:=>读者续借次数达到上限，请归还再借！";
                AG = AG + "读者[" + AB + "]续借失败原因:=>读者续借次数达到上限，请归还再借！";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }

            DateTime returnTime = ck.ShouldReturnTime;

            if (dtc.Rows[0]["续借期限类型"].ToString() == "M")
            {

                returnTime = returnTime.AddMonths(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
            }
            else if (dtc.Rows[0]["续借期限类型"].ToString() == "D")
            {
                returnTime = returnTime.AddDays(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
            }
            else
            {
                returnTime = returnTime.AddYears(int.Parse(dtc.Rows[0]["续借期限"].ToString()));
            }

            bool flag = BLL.UpdateChangeKUReBackTime(AB, returnTime, ck.OnceBorrowCount + 1);
            if (!flag)
            {
                AF = AF + "图书【" + TM + "】续借处理失败 原因:=>修改归还时间出错！";
                AG = AG + "读者[" + AB + "]续借失败原因:=>修改归还时间出错！";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
               
            }
            var book = BLL.GetBooksInfoByBarcode(AB);
            //配置Entity
            ChangeLogInfo model1 = new ChangeLogInfo
            {
                OperateType = "X",
                BarCode = AB,
                LoginAccount = AB,
                ReaderCode = book.ReaderCode,
                DealTime = DateTime.Now,
                Penalty = 0.00m,
                Operator = 99,
                ID = book.ID
            };


            //在流通库中新增一条记录
            bool res = BLL.InsertLTKOneInfo(model1);
            if (res)
            {
                head = "301NNY" + DateTime.Now.ToString("yyyyMMdd     HHmmss") + "AO";
                AF = AF + "图书【" + TM + "】续借处理成功！ 应还日期(" + yghrq + ")";
                AG = AG + "成功续借" + AB + "=>" + TM;
                AA = "|AA" + AA;
                AB = "|AB" + AB;
                AJ = "|AJ" + TM;
                AH = "|AH" + returnTime.ToString();
                CH = "|CH" + CH;
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }
            else
            {
                AF = AF + "图书【" + TM + "】续借处理失败 原因:=>插入流通日志失败！";
                AG = AG + "读者[" + AB + "]续借失败原因:=>插入流通日志失败！";
                return head + AA + AB + AJ + AH + BT + CI + BH + BV + CK + BK + AF + AG + AY;
            }

            
        }

        /*
         */
        #endregion

        #region 63 查询读者
        /*
         * 6301920141202    161543  YAOGT|AA001|ACLJZ|AD|BP1|BQ20|AY1AZECD7
         * 6301920150321    120258  Y       AO|AA0000196|BP1|BQ20|AY1AZF2C4
         * 6301920150321    133521  Y       AO|AA0000196|AD888888|BP1|BQ20|AY4AZF073
EF3F
         * 6400120141202    161047000100000001 000000000000AO001|AA0100000369090|AE林晴朗
         * |CF0.0|BLY|CQY|BV0.00|JE0.0|JF0.0|XV0.00|XR0.0|XC12.8|BZ0020|LL0001/0015|GL0000/0005|XTGT_001
         * |XD2114-09-27|AS101646656|AF|AG|MC|SR0|AY4AZ608F
         * 
         * 
         */
        public string ReceivQueryReader(string st)
        {
            List<string> li = Exstring(st);
            string AA = "";
            string AC = "";
            string AD = "";
            string BP = "";
            string BQ = "";
            string AY = "";

            for (int i = 0; i < li.Count; i++)
            {
                string str = li[i].Substring(0, 2);

                string str1 = li[i].ToString().Substring(2).Trim();

                if (!string.IsNullOrWhiteSpace(str1))
                {

                    if (str == "AA" && string.IsNullOrWhiteSpace(AA))
                    {
                        AA = li[i].ToString().Substring(2).Trim();

                    }
                    else if (str == "AD" && string.IsNullOrWhiteSpace(AD))
                    {
                        AD = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "BP" && string.IsNullOrWhiteSpace(BP))
                    {
                        BP = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "BQ" && string.IsNullOrWhiteSpace(BQ))
                    {
                        BQ = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "AY" && string.IsNullOrWhiteSpace(AY))
                    {
                        AY = li[i].ToString().Substring(2).Trim();
                    }
                    else if (str == "AC" && string.IsNullOrWhiteSpace(AC))
                    {
                        AC = li[i].ToString().Substring(2).Trim();
                    }
                }
            }

            string ok = "";
            string AE = "|AE";//姓名
            string CF = "|CF";//0.0
            string BL = "|BL";//验证读者：Y表示读者存在，N表示读者不存在
            string CQ = "|CQ"; //验证密码：Y表示读者密码正确，N表示读者密码错误
            string BV = "|BV";//押金
            string JE = "|JE"; //读者预付款
            string JF = "|JF";//读者欠款
            string XV = "|XV";//0.00
            string XR = "|XR";//押金保证系数
            string XC = "|XC";//所借图书总额
            string BZ = "|BZ";//允许最大借书数
            string LL = "|LL";//0001/0015
            string GL = "|GL";//"0000/0005"
            string XT = "|XT";//读者类型
            string XD = "|XD";//证过期日期
            string AS = "";//当前借阅图书条码
            string AF = "|AF";//提示信息
            string AG = "|AG";//打印信息
            string MC = "|MC";
            string SR = "|SR";
            string SSA = "";//条形码字符串
            string head = "64001" + SendbackTime() + "0001" + "0001" + "0000" + "000000000000AO";
            try
            {
                var dtUser = rib.GetUser(AA);

                if (dtUser.Rows.Count > 0)
                {
                    string mm = "";
                    AE = AE + dtUser.Rows[0]["姓名"].ToString().Trim();
                    JF = JF + dtUser.Rows[0]["欠罚款"].ToString().Trim();
                    BV = BV + dtUser.Rows[0]["押金"].ToString().Trim();
                    XT = XT + dtUser.Rows[0]["读者级别"].ToString().Trim();
                    XD = XD + dtUser.Rows[0]["失效日期"].ToString().Trim();
                    BZ = BZ + dtUser.Rows[0]["可外借"].ToString().Trim();
                    mm = dtUser.Rows[0]["密码"].ToString().Trim();
                    if (mm == AD)
                    {
                        CQ = CQ + "Y";
                        string sql11 = "select 条形码 from 流通库 where 读者条码='" + AA + "'";
                        DataTable dt = BLL.GetSipLendBookPriceSUM(AA);
                        decimal sumpirce = 0;

                        if (dt.Rows.Count > 0)
                        {
                            XC = XC + dt.Rows[0]["price"].ToString();
                        }

                        XC = XC + sumpirce.ToString();
                    }
                    else
                    {
                        CQ = CQ + "N";
                    }
                }
                else
                {
                    BL = BL + "N";
                }


                AA = "|AA" + AA;
                AY = "|AY3AZEF2F";
                ok = head + AA + AE + CF + BL + CQ + BV + JE + JF + XV + XR + XC + BZ + LL + GL + XT + XD + AS + AF + AG + MC + SR + AY;
                return ok;
            }catch(Exception ex)
            {
                AF += "查询读者信息出错";
                AG += "查询读者信息出错";
                LogManager.WriteLogs(ex.Message, ex.StackTrace, LogFile.Error);
                ok = head + AA + AE + CF + BL + CQ + BV + JE + JF + XV + XR + XC + BZ + LL + GL + XT + XD + AS + AF + AG + MC + SR + AY;
                return ok;
            }
        }

        public string SendQueryReader(string readerid)
        {
            string ok = "";
            return ok;
        }

        #endregion


        #region 99处理
        //99<status code><max print width><protocol version> 
        //9900522.00AY2AZFCA0
        /*98<on-line status><checkin ok>
         * <checkout ok><ACS renewal policy><status update ok><off-line ok>
         * <timeout period><retries allowed>
         * <date / time sync><protocol version><institution id>
         * <library name><supported messages >
         * <terminal location><screen message>
         * <print line>
         */
        //send 98YYYNYN01000320141201    0256542.00AOGT|AMGT|AN|AF连接ACS_Server成功!|AG|BX|AY1AZDA74
        private string ReceivConnection(string ReceiveMessage)
        {
            string sendback = "";
            sendback = "98YYYNYN010003" + DateTime.Now.ToString("yyyyMMdd     HHmmss") + "2.00AOGT|AMGT|AN|AF连接ACS_Server成功!|AG|BX|AYXHXTSG";
            return sendback;

        }
        #endregion

        #endregion

        #region 控件按钮事件

        /// <summary>
        /// 退出程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        
        /// <summary>
        /// 保存设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                ConfigHelper.UpdateOrCreateConnectionString(ConfigurationFile.AppConfig, "WayLibDB", textBox1.Text, textBox1.Text);
                ConfigHelper.UpdateOrCreateAppSetting(ConfigurationFile.AppConfig, "IP", textBox2.Text);
                ConfigHelper.UpdateOrCreateAppSetting(ConfigurationFile.AppConfig, "Port", textBox3.Text);

                Application.Restart();

            }
            catch(Exception ex)
            {
                LogManager.WriteLogs(ex.StackTrace, ex.Message,LogFile.Error);
            }
        }

        /// <summary>
        /// 连接设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedTab = tabControl1.TabPages[1];

        }

        /// <summary>
        /// 链接数据库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string connStr = textBox1.Text;
            try
            {
                SqlConnection conn = new SqlConnection(connStr);
                conn.Open();
                conn.Close();
            }
            catch (Exception ex)
            {
                richTextBox1.Text = richTextBox1.Text + "连接数据库失败：" + ex.Message + "";
            }
        }

        #endregion

        #region  更新richtextbox控件的代理
        /// <summary>
        ///     更新richtextbox控件的代理
        /// </summary>
        /// <param name="log">传入的字符串</param>
        private delegate void SetLogCallBack(string log);

        /// <summary>
        ///     更新richtextbox控件的具体方法
        /// </summary>
        /// <param name="str">传入的字符串</param>
        private void SetLog(string str)
        {
            if (richTextBox1.InvokeRequired)
            {
                SetLogCallBack d = SetLog;
                Invoke(d, new object[] { str.Trim() });
            }
            else
            {
                richTextBox1.AppendText(str);
            }
        }


        #endregion

        #region 命令解析
        /// <summary>
        ///     把命令解析成一个个单个信息存贮在list<>里
        /// </summary>
        /// <param name="st"></param>
        /// <returns></returns>
        public List<string> Exstring(string st)
        {
            var li = new List<string>();

            string[] arr = st.Split('|');
            for (int i = 0; i < arr.Length; i++)
            {
                li.Add(arr[i]);
            }

            return li;
        }


        private string SendbackTime()
        {
            return DateTime.Now.ToString("yyyyMMdd     HHmmss");
        }
        #endregion

    }


}
